import { getUserTableStyles as getUserTableStylesAPI } from '~/api/tableStyle'
import { saveBatch } from '~/api/tableStyle'
export default {
  namespaced: true,
  state(){
    return {
      tableStyles: []
    }
  },
  mutations:{
    setTableStyle(state, tableStyle) {
      state.tableStyles = tableStyle
    },
    replacePartial(state, partialArray){
      const arr = state.tableStyles.filter(item => {
        const ret = partialArray.find(item1 => item1.iid === item.iid)
        return ret ? false : true
      })

      state.tableStyles = arr.concat(partialArray)
    }

  },
  actions:{
    getUserTableStyles({ commit }){
      getUserTableStylesAPI().then(res => {
        if(res.code !==1) return
        commit('setTableStyle', res.data)
      })
    },
    updateTableStyle({ commit }, tableStyleArray){
      return new Promise((resolve, reject) => {
        saveBatch(tableStyleArray).then(res => {
          if(res.code !==1) return
          // 请求成功后修改 store 中对应主键的数据
          commit('replacePartial', tableStyleArray)
          resolve(res)
        })
      })
    }

  }
}